package br.rafael.mulock.controle_de_estoque.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JOptionPane;

import br.rafael.mulock.controle_de_estoque.modelo.pojo.Usuario;
import br.rafael.mulock.controle_de_estoque.utilitarios.Texto;

public class ConexaoDAO {

	private static EntityManagerFactory emf = null;
	
	private static Usuario usuario = null;
	
	private static EntityManager em = null;
	
	public static String getLoginUsuario() {
		return usuario != null ? usuario.getLogin() : null;
	}
	
	public static EntityManager getEntityManager() {
		if (em != null && em.isOpen()) {
			return em;
		} else {
			if (emf != null) {
				em = emf.createEntityManager();
				return em;
			} else {
				return null;
			}
		}
	}
	
	private ConexaoDAO() {
		super();
	}
	
	public static void abrirConexao(String login, String senha) throws Exception {
		Map<String, String> tags = new HashMap<String, String>();
		tags.put("hibernate.connection.username", login);
		tags.put("hibernate.connection.password", senha);
		emf = Persistence.createEntityManagerFactory("EstoquePU", tags);
		EntityManager em = ConexaoDAO.getEntityManager();
		Query query = em.createQuery("select e from Usuario e where e.login = :login");
		query.setParameter("login", login);
		query.setMaxResults(1);
		try {
			@SuppressWarnings("unchecked")
			List<Usuario> listaUsuario = (ArrayList<Usuario>) query.getResultList();
			if (listaUsuario == null || listaUsuario.isEmpty()) {
				JOptionPane.showMessageDialog(null, new Texto().get("mensagem.usuario.nao.cadastrado"));
			} else {
				usuario = listaUsuario.get(0);
			}
		} catch (Exception e) {
			emf.close();
			throw new Exception(new Texto().get("erro.acessar.sistema.usuario.senha.incorretos"));
		}
	}

	public static boolean verificarConexao() {
		if (getLoginUsuario() != null) {
			if (getEntityManager() != null) {
				getEntityManager().close();
				return true;
			 } else {
				 return false;
			 }
		} else {
			return false;
		}
	}

	public static void logoff() {
		if (emf != null) {
			emf.close();
		}
		
		if (usuario != null) {
			usuario = null;
		}
	}
}
